#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "cmsis_os2.h"
#include "iot_errno.h"
#include "iot_uart.h"
#include "ohos_init.h"

#define UART_TASK_STACK_SIZE (1024 * 8)
#define UART_TASK_PRIO 25
#define UART_BUFF_SIZE 1000
#define UART1 1
#define TASK_DELAY_1S 1000000

static const char *data = "uart_task\r\n";

/**
 * @brief uart task send data through uart1 and receive data through uart1
 *
 */
static void UartTask(void)
{
    uint8_t uart_buff[UART_BUFF_SIZE] = {1,2};
    uint8_t *uart_buff_ptr = uart_buff;
    uint8_t ret;

    IotUartAttribute uart_attr = {
        .baudRate = 9600,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
    };

    // Initialize uart driver
    ret = IoTUartInit(UART1, &uart_attr);
    if (ret != IOT_SUCCESS) {
        printf("Failed to init uart! Err code = %d\n", ret);
        return;
    }

    while (1) {
        printf("=======================================\r\n");
        printf("*************UART_example**************\r\n");
        printf("=======================================\r\n");

        // send data through uart1
        IoTUartWrite(UART1, (unsigned char *)data, strlen(data));

        // receive data through uart1
        IoTUartRead(UART1, uart_buff_ptr, UART_BUFF_SIZE);

        printf("Uart1 read data:%s\n", uart_buff_ptr);
        usleep(TASK_DELAY_1S);
    }
}

static void UartExampleEntry(void)
{
    osThreadAttr_t attr;

    attr.name = "UartTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = UART_TASK_STACK_SIZE;
    attr.priority = UART_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)UartTask, NULL, &attr) == NULL) {
        printf("Failed to create UartTask!\n");
    }
}

APP_FEATURE_INIT(UartExampleEntry);